package com.dongdongshop.controller;

import com.dongdongshop.pojo.TbItemCat;
import com.dongdongshop.service.ItemCatService;
import com.dongdongsop.data.AjaxResult;
import com.dongdongsop.em.ResultEnum;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("itemCat")
public class ItemCatController {

    @DubboReference
    private ItemCatService itemCatService;

    //跳转商品分类管理页面
    @RequestMapping("toItemCat")
    public String toItemCat(){
        return "admin/item_cat";
    }

    //商品分类查询
    @RequestMapping("itemCatInfo")
    @ResponseBody
    public List<TbItemCat> itemCatInfo(Long id){
        List<TbItemCat> itemCatList = itemCatService.itemCatInfo(id);
        return itemCatList;
    }

    //跳转商品分类添加页面
    @RequestMapping("toItemCatAdd")
    public String toItemCatAdd(){
        return "item_cat/add";
    }

    //商品分类添加
    @RequestMapping("itemCatAdd")
    @ResponseBody
    public AjaxResult itemCatAdd(TbItemCat itemCat){
        try {
            int i = itemCatService.itemCatAdd(itemCat);
            return AjaxResult.OK().setData(i);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    //跳转商品分类修改页面并回显
    @RequestMapping("getItemCatById")
    public String getItemCatById(Long id, Model model){
        TbItemCat itemCat = itemCatService.getItemCatById(id);
        model.addAttribute("itemCat",itemCat);
        return "item_cat/update";
    }

    //商品分类修改
    @RequestMapping("updateItemCat")
    @ResponseBody
    public AjaxResult updateItemCat(TbItemCat itemCat){
        try {
            int i = itemCatService.updateItemCat(itemCat);
            return AjaxResult.OK().setData(i);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    //商品分类删除
    @RequestMapping("deleteId")
    @ResponseBody
    public AjaxResult deleteId(Long id){
        try {
            List<TbItemCat> itemCatList = itemCatService.itemCatInfo(id);
            if (itemCatList.size() > 0){
                return AjaxResult.R(ResultEnum.ARGS_FAILE);
            }else {
                int i = itemCatService.deleteId(id);
                return AjaxResult.OK().setData(i);

            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }
}
